package com.yupi.springbootinit.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.manager.AIManager;
import com.yupi.springbootinit.mapper.CourseWatchRecordMapper;
import com.yupi.springbootinit.model.entity.Course;
import com.yupi.springbootinit.model.entity.CourseWatchRecord;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.vo.CourseVO;
import com.yupi.springbootinit.model.vo.CourseWatchStatsVO;
import com.yupi.springbootinit.service.CourseService;
import com.yupi.springbootinit.service.CourseWatchService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CourseWatchServiceImpl extends ServiceImpl<CourseWatchRecordMapper, CourseWatchRecord> 
        implements CourseWatchService {

    @Resource
    private CourseService courseService;

    @Resource
    private AIManager aiManager;

    @Override
    public boolean recordWatchDuration(long courseId, long chapterId, int duration, User loginUser) {
        CourseWatchRecord record = new CourseWatchRecord();
        record.setUserId(loginUser.getId());
        record.setCourseId(courseId);
        record.setChapterId(chapterId);
        record.setWatchDuration(duration);
        record.setWatchTime(new Date());
        return this.save(record);
    }

    @Override
    public List<CourseWatchStatsVO> getUserWatchStats(Long userId) {
        // 查询用户的所有观看记录
        List<CourseWatchRecord> records = this.lambdaQuery()
                .eq(CourseWatchRecord::getUserId, userId)
                .list();
                
        // 按课程ID分组统计
        Map<Long, List<CourseWatchRecord>> courseRecords = records.stream()
                .collect(Collectors.groupingBy(CourseWatchRecord::getCourseId));
                
        // 获取所有相关课程信息
        List<Long> courseIds = new ArrayList<>(courseRecords.keySet());
        Map<Long, Course> courseMap = courseService.listByIds(courseIds).stream()
                .collect(Collectors.toMap(Course::getId, course -> course));
                
        // 统计每个课程的观看数据
        return courseRecords.entrySet().stream().map(entry -> {
            Long courseId = entry.getKey();
            List<CourseWatchRecord> courseWatchRecords = entry.getValue();
            
            CourseWatchStatsVO statsVO = new CourseWatchStatsVO();
            statsVO.setCourseId(courseId);
            statsVO.setCourseName(courseMap.get(courseId).getTitle());
            statsVO.setWatchCount(courseWatchRecords.size());
            
            // 计算总时长
            long totalDuration = courseWatchRecords.stream()
                    .mapToLong(CourseWatchRecord::getWatchDuration)
                    .sum();
            statsVO.setTotalDuration(totalDuration);
            
            // 格式化时长
            statsVO.setFormattedDuration(formatDuration(totalDuration));
            
            return statsVO;
        }).collect(Collectors.toList());
    }
    
    /**
     * 将秒数转换为时分秒格式
     */
    private String formatDuration(long seconds) {
        long hours = seconds / 3600;
        long minutes = (seconds % 3600) / 60;
        long secs = seconds % 60;
        return String.format("%02d:%02d:%02d", hours, minutes, secs);
    }

    @Override
    public List<CourseVO> getRecommendCourses(Long userId) {
        // 1. 获取用户观看记录
        List<CourseWatchStatsVO> watchStats = this.getUserWatchStats(userId);
        
        // 2. 获取所有课程信息
        List<Course> allCourses = courseService.list();
        
        // 3. 构建 AI 分析所需的数据
        StringBuilder prompt = new StringBuilder();
        prompt.append("根据用户观看记录推荐课程。\n\n");
        prompt.append("用户观看记录：\n");
        for (CourseWatchStatsVO stat : watchStats) {
            prompt.append(String.format("- 课程：%s，观看时长：%s，观看次数：%d\n", 
                    stat.getCourseName(), 
                    stat.getFormattedDuration(),
                    stat.getWatchCount()));
        }
        
        prompt.append("\n所有可选课程：\n");
        for (Course course : allCourses) {
            prompt.append(String.format("- ID：%d，课程名：%s\n", 
                    course.getId(), 
                    course.getTitle()));
        }
        
        prompt.append("\n请分析用户的学习偏好，推荐5门最适合的课程，只返回课程ID，用逗号分隔。");
        
        // 4. 调用星火 AI 接口获取推荐
        String aiResponse = aiManager.sendMsgToXingHuoAICourse(true,prompt.toString());
        if (aiResponse == null) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "AI 推荐失败");
        }

        //todo 让AI只返回ID
        // 5. 解析 AI 返回的课程 ID
        String[] recommendIds = aiResponse.split(",");
        List<Long> courseIds = Arrays.stream(recommendIds)
                .map(String::trim)
                .map(Long::parseLong)
                .collect(Collectors.toList());
                
        // 6. 获取推荐课程的详细信息
        List<Course> recommendCourses = courseService.listByIds(courseIds);
        
        // 7. 转换为 VO 对象
        return recommendCourses.stream().map(course -> {
            CourseVO courseVO = new CourseVO();
            courseVO.setId(course.getId());
            courseVO.setTitle(course.getTitle());
            courseVO.setDescription(course.getDescription());
            courseVO.setImage(course.getImage());
            // TODO: 设置其他必要字段
            return courseVO;
        }).collect(Collectors.toList());
    }
} 